﻿Imports System.Globalization

Public Class frmCompras

    Dim controller As New ControllerSigeco.controller_compras
    Dim controllerStock As New ControllerSigeco.controller_stock

    Private Sub cbxVto_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbxVto.CheckedChanged
        fechaVto.Enabled = cbxVto.Checked
    End Sub

    Private Sub btnCancelar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancelar.Click
        Me.Close()
    End Sub

    Private _codProveedor As Integer = 0

    Public Property codProveedor() As Integer
        Get
            Return _codProveedor
        End Get
        Set(ByVal value As Integer)
            _codProveedor = value
        End Set
    End Property

    Private _codMercaderia As Integer = 0

    Public Property codMercaderia() As Integer
        Get
            Return _codMercaderia
        End Get
        Set(ByVal value As Integer)
            _codMercaderia = value
        End Set
    End Property

    Private _codMercaderiaDetalle As Integer = 0

    Public Property codMercaderiaDetalle() As Integer
        Get
            Return _codMercaderiaDetalle
        End Get
        Set(ByVal value As Integer)
            _codMercaderiaDetalle = value
        End Set
    End Property

    Private _codCompra As Integer = 0

    Public Property codCompra() As Integer
        Get
            Return _codCompra
        End Get
        Set(ByVal value As Integer)
            _codCompra = value
        End Set
    End Property

    Private _codOrdenCompra As Integer = 0

    Public Property codOrdenCompra() As Integer
        Get
            Return _codOrdenCompra
        End Get
        Set(ByVal value As Integer)
            _codOrdenCompra = value
        End Set
    End Property

    Private m_frmBusMercaderia As frmMercaderiaBuscador
    Public Property frmBusMercaderia() As frmMercaderiaBuscador
        Get
            Return m_frmBusMercaderia
        End Get
        Set(ByVal value As frmMercaderiaBuscador)
            m_frmBusMercaderia = value
        End Set
    End Property

    Private m_frmBusProveedor As frmProveedorBuscador
    Public Property frmBusProveedor() As frmProveedorBuscador
        Get
            Return m_frmBusProveedor
        End Get
        Set(ByVal value As frmProveedorBuscador)
            m_frmBusProveedor = value
        End Set
    End Property

    Private Sub btnBuscProveedor_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBuscProveedor.Click

        frmBusProveedor = New frmProveedorBuscador
        frmBusProveedor.ShowDialog()
        txtProveedor.Text = frmBusProveedor.ProveedorDesc
        codProveedor = frmBusProveedor.codProveedor
        If codProveedor > 0 Then
            btnBuscMercaderia.Focus()
        End If

    End Sub

    Private Sub btnBuscOrdenCompra_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBuscOrdenCompra.Click



    End Sub

    Private Sub btnBuscMercaderia_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBuscMercaderia.Click

        frmBusMercaderia = New frmMercaderiaBuscador
        frmBusMercaderia.ShowDialog()
        txtMercaderia.Text = frmBusMercaderia.MercaderiaDesc
        codMercaderia = frmBusMercaderia.codMercaderia
        If codMercaderia > 0 Then
            txtcantidad.Focus()
        End If

    End Sub

    Private Sub txtcantidad_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtcantidad.Leave
        If IsNumeric(txtcantidad.Text) And IsNumeric(txtprecio.Text) Then
            txttotal.Text = txtcantidad.Text * txtprecio.Text
        End If
    End Sub

    Private Sub frmCompras_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        dgvdetalle.AutoGenerateColumns = False
        btnImprimir.Visible = False
        cboTipo.SelectedIndex = 0
        cboEstado.SelectedIndex = 0

        oiml.CargarCombos(cboIVA, "Impuesto", "idImpuesto", controllerStock.get_impuestos(oiml.dbConn, 0, ""))
        CargarCompras()
    End Sub

    Private Sub CargarComprasDetalle()
        Try

            codMercaderia = 0
            codMercaderiaDetalle = 0
            txtMercaderia.Text = ""
            txtcantidad.Text = 1
            txtprecio.Text = 0
            txttotal.Text = 0

            Dim ds As New DataTable
            ds = controller.get_Compras_Detalles_All(oiml.dbConn, codCompra)

            If Not ds Is Nothing Then
                dgvdetalle.DataSource = ds
            Else
                dgvdetalle.DataSource = Nothing
            End If

        Catch ex As Exception
            MessageBox.Show("Error: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

        End Try

    End Sub

    Dim ci As CultureInfo

    Private Sub CargarCompras()
        Try
            If codCompra > 0 Then

                Dim ds As New DataTable
                ds = controller.get_Compras_ByID(oiml.dbConn, codCompra)

                If Not ds Is Nothing Then

                    txtActualizadoFecha.Text = ds.Rows(0)("actualizadoFecha_")
                    txtActualizadoPor.Text = ds.Rows(0)("actualizadoPor")

                    If Not ds.Rows(0)("nroOrden") Is DBNull.Value Then
                        codOrdenCompra = ds.Rows(0)("idOrdenCompra")
                        txtOrdenCompra.Text = ds.Rows(0)("nroOrden")
                    End If

                    'ci = Thread.CurrentThread.CurrentCulture

                    txtProveedor.Text = ds.Rows(0)("proveedor")
                    codProveedor = ds.Rows(0)("idProveedor")
                    txtSaldo.Text = Decimal.Parse(ds.Rows(0)("totalFacturaSaldo").ToString).ToString("N0")
                    'ds.Rows(0)("totalFacturaSaldo").ToString("D")
                    txtTotalFactura.Text = Decimal.Parse(ds.Rows(0)("totalFactura").ToString).ToString("N0")
                    'ds.Rows(0)("totalFactura").ToString("D")
                    txtIVA.Text = Decimal.Parse(ds.Rows(0)("totalFacturaIVA").ToString).ToString("N0")
                    'ds.Rows(0)("totalFacturaIVA").ToString("D")
                    nroFactura.Text = ds.Rows(0)("nroComprobante")
                    fechaFactura.Value = ds.Rows(0)("fecha")

                    If Not ds.Rows(0)("fechaVencimiento") Is DBNull.Value Then
                        fechaVto.Value = ds.Rows(0)("fechaVencimiento")
                    End If

                    cboEstado.Text = ds.Rows(0)("estado")

                    ControlEstados()

                    cboTipo.Text = ds.Rows(0)("condicion")

                    'btnGrabar.Enabled = True
                    'btnEliminar.Enabled = True

                    CargarComprasDetalle()

                End If

            Else
                cboEstado.Text = "EN PROCESO"
                nroFactura.Focus()

            End If

        Catch ex As Exception
            MessageBox.Show("Error: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

        End Try

    End Sub

    Private Sub ControlEstados()

        If cboEstado.Text = "APROBADA" Then

            nroFactura.Enabled = False
            fechaFactura.Enabled = False
            fechaVto.Enabled = False
            cboTipo.Enabled = False

            btnBuscMercaderia.Enabled = False
            btnBuscProveedor.Enabled = False
            btnBuscOrdenCompra.Enabled = False

            btnGrabar.Enabled = False
            btnAgregarDetalle.Enabled = False
            btnConfirmar.Enabled = False
            btnEliminar.Enabled = False
            btnEliminarDetalle.Enabled = False

            txtcantidad.Enabled = False
            txtprecio.Enabled = False
            cboIVA.Enabled = False

            btnCancelar.Focus()

        ElseIf cboEstado.Text = "ANULADA" Then

            nroFactura.Enabled = False
            fechaFactura.Enabled = False
            fechaVto.Enabled = False
            cboTipo.Enabled = False

            btnBuscMercaderia.Enabled = False
            btnBuscProveedor.Enabled = False
            btnBuscOrdenCompra.Enabled = False

            btnGrabar.Enabled = False
            btnAgregarDetalle.Enabled = False
            btnEliminarDetalle.Enabled = False
            btnConfirmar.Enabled = False
            btnEliminar.Enabled = False
            btnAnular.Enabled = False

            txtcantidad.Enabled = False
            txtprecio.Enabled = False
            cboIVA.Enabled = False

            btnCancelar.Focus()

        End If

    End Sub

    Private Function ValidarCampos() As Boolean

        Dim controlCampos As Boolean = False

        If nroFactura.Text = "" Then
            ErrorProvider1.SetError(nroFactura, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider1.SetError(nroFactura, "")
        End If        '

        If txtProveedor.Text = "" Then
            ErrorProvider1.SetError(txtProveedor, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider1.SetError(txtProveedor, "")
        End If        '

        Return controlCampos

    End Function

    Private Function ValidarCamposDetalle() As Boolean

        Dim controlCampos As Boolean = False

        If txtMercaderia.Text = "" Then
            ErrorProvider1.SetError(txtMercaderia, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider1.SetError(txtMercaderia, "")
        End If        '

        If txtcantidad.Text = "" Or Not IsNumeric(txtcantidad.Text) Then
            ErrorProvider1.SetError(txtcantidad, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider1.SetError(txtcantidad, "")
        End If        '

        If txtprecio.Text = "" Or Not IsNumeric(txtprecio.Text) Then
            ErrorProvider1.SetError(txtprecio, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider1.SetError(txtprecio, "")
        End If        '

        Return controlCampos

    End Function

    Private Sub btnEliminar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEliminar.Click
        If codCompra > 0 Then

            If MessageBox.Show("Desea eliminar el registro seleccionado?", "Compras", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then

                If controller.Delete_Compras(oiml.dbConn, codCompra, oiml.idUsuario) Then
                    Me.Close()

                Else
                    MessageBox.Show("Error: " & controller.MessageError.Message, "Compras", MessageBoxButtons.OK, MessageBoxIcon.Error)

                End If

            End If

        End If

    End Sub

    Private Sub btnGrabar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGrabar.Click

        If ValidarCampos() Then
            Exit Sub
        End If

        Dim fechaVencimiento As String = ""

        If cbxVto.Checked Then
            fechaVencimiento = fechaVto.Value
        End If

        If codCompra = 0 Then
            codCompra = controller.Insert_Compras(oiml.dbConn, nroFactura.Text, fechaFactura.Value, _
                                                  codProveedor, fechaVencimiento, cboTipo.Text, _
                                                  cboEstado.Text, codOrdenCompra, 0, txtTotalFactura.Text, _
                                                  txtSaldo.Text, txtIVA.Text, oiml.idUsuario)

            If codCompra > 0 Then
                CargarCompras()
                MessageBox.Show("Registro grabado con exito!", "Compras", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

            Else
                MessageBox.Show("Error: " & controller.MessageError.Message, "Compras", MessageBoxButtons.OK, MessageBoxIcon.Error)

            End If

        Else
            If controller.Update_Compras(oiml.dbConn, codCompra, nroFactura.Text, fechaFactura.Value, _
                                                  codProveedor, fechaVencimiento, cboTipo.Text, _
                                                  cboEstado.Text, codOrdenCompra, 0, txtTotalFactura.Text, _
                                                  txtSaldo.Text, txtIVA.Text, oiml.idUsuario) Then
                CargarCompras()
                MessageBox.Show("Registro grabado con exito!", "Compras", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)


            Else
                MessageBox.Show("Error: " & controller.MessageError.Message, "Compras", MessageBoxButtons.OK, MessageBoxIcon.Error)

            End If

        End If

    End Sub

    Private Sub dgvdetalle_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles dgvdetalle.KeyDown
        If e.KeyCode = Keys.Enter Then
            If dgvdetalle.SelectedRows.Count > 0 Then

                codMercaderiaDetalle = dgvdetalle.SelectedRows(0).Cells(0).Value

            End If
        End If
    End Sub

    Private Sub dgvdetalle_DoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dgvdetalle.DoubleClick
        If dgvdetalle.SelectedRows.Count > 0 Then

            codMercaderiaDetalle = dgvdetalle.SelectedRows(0).Cells(0).Value

        End If
    End Sub

    Private Sub dgvdetalle_CellClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvdetalle.CellClick
        Try

            If dgvdetalle.SelectedRows.Count > 0 Then

                codMercaderiaDetalle = dgvdetalle.SelectedRows(0).Cells(0).Value

            End If

        Catch ex As Exception
            MessageBox.Show("Error: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub btnEliminarDetalle_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEliminarDetalle.Click

        If codMercaderiaDetalle > 0 Then

            If MessageBox.Show("Desea eliminar el registro seleccionado?", "Compras", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then

                If controller.Delete_Compras_Detalle(oiml.dbConn, codMercaderiaDetalle, oiml.idUsuario, codCompra) Then
                    CargarCompras()

                Else
                    MessageBox.Show("Error: " & controller.MessageError.Message, "Compras", MessageBoxButtons.OK, MessageBoxIcon.Error)

                End If

            End If

        End If

    End Sub

    Private Sub btnAgregarDetalle_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAgregarDetalle.Click

        If ValidarCamposDetalle() Then
            Exit Sub
        End If

        If codCompra = 0 Then
            codCompra = controller.Insert_Compras(oiml.dbConn, nroFactura.Text, fechaFactura.Value, _
                                                  codProveedor, fechaVto.Value, cboTipo.Text, _
                                                  cboEstado.Text, codOrdenCompra, 0, txtTotalFactura.Text, _
                                                  txtSaldo.Text, txtIVA.Text, oiml.idUsuario)
        Else
            If controller.Update_Compras(oiml.dbConn, codCompra, nroFactura.Text, fechaFactura.Value, _
                                                  codProveedor, fechaVto.Value, cboTipo.Text, _
                                                  cboEstado.Text, codOrdenCompra, 0, txtTotalFactura.Text, _
                                                  txtSaldo.Text, txtIVA.Text, oiml.idUsuario) Then
            Else
                MessageBox.Show("Error: " & controller.MessageError.Message, "Compras", MessageBoxButtons.OK, MessageBoxIcon.Error)

            End If

        End If

        If codCompra > 0 And codMercaderia > 0 Then

            If controller.Insert_Compras_Detalle(oiml.dbConn, codCompra, codMercaderia, _
                                                 txtcantidad.Text, txtprecio.Text, cboIVA.SelectedValue, txttotal.Text, oiml.idUsuario) Then
                CargarCompras()
                MessageBox.Show("Registro grabado con exito!", "Compras", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            Else
                MessageBox.Show("Error: " & controller.MessageError.Message, "Compras", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End If

        End If

    End Sub

    Private Sub btnConfirmar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConfirmar.Click

        If codCompra > 0 Then

            If controller.Update_Compras_Estado(oiml.dbConn, codCompra, "APROBADA", oiml.idUsuario) Then
                CargarCompras()
                MessageBox.Show("Registro confirmado con exito!", "Compras", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            Else
                MessageBox.Show("Error: " & controller.MessageError.Message, "Compras", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End If

        End If

    End Sub

    Private Sub cboTipo_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboTipo.SelectedIndexChanged

        If cboTipo.Text = "CREDITO" Then
            cbxVto.Checked = True
        Else
            cbxVto.Checked = False
        End If

    End Sub

    Private Sub txtprecio_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtprecio.Leave
        If IsNumeric(txtcantidad.Text) And IsNumeric(txtprecio.Text) Then
            txttotal.Text = txtcantidad.Text * txtprecio.Text
        End If
    End Sub

    Private Sub btnAnular_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAnular.Click
        If codCompra > 0 Then
            If MessageBox.Show("Desea anular el registro seleccionado?", "Compras", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then

                If controller.Update_Compras_Estado(oiml.dbConn, codCompra, "ANULADA", oiml.idUsuario) Then
                    Me.Close()

                Else
                    MessageBox.Show("Error: " & controller.MessageError.Message, "Compras", MessageBoxButtons.OK, MessageBoxIcon.Error)

                End If

            End If
        End If
    End Sub

End Class